package Gui.Dialogs;

import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.GridLayout;
import java.util.ArrayList;

import javax.swing.JDialog;
import javax.swing.JLabel;

import Gui.GameFrame;
import Main.Defines;
import PlayerManager.Player;

public class GameOverStatsDialog extends JDialog {
	private void buildUIContents() {
		JLabel infoLabel = new JLabel();
		String infoString = "";
		infoString += "<html>";
		ArrayList<Player> winningPlayers = new ArrayList<Player>();
		int winningScore = Integer.MIN_VALUE;
		// add players to label and check for winner
		for (Player player : Defines.PLM.getPlayerList()) {
			infoString += player.getGameOverToString();
			// if current Score is less than winningScore, winningPlayers list,
			// add this player, update winningScore
			if (winningScore < player.getCash() - player.getLoan()) {
				winningPlayers = new ArrayList<Player>();
				winningPlayers.add(player);
				winningScore = player.getCash() - player.getLoan();
			} else if (winningScore == player.getCash() - player.getLoan()) {
				// there is a tie for best score
				winningPlayers.add(player);
			}
		}
		infoString += infoString += "<br>";
		infoString += "</br>";
		// print winning players
		for( Player winner : winningPlayers){
			infoString += winner.getName();
			// add " and" string if the winningPlayers list is greater than 0 and is not the last winner in the list
			if(winningPlayers.size() > 0 && winner.equals(winningPlayers.get(winningPlayers.size()-1))){
				infoString += " and";
			}
		}
		infoString += " won!!";
		infoString += "</html>";
		infoLabel.setText(infoString);
		add(infoLabel);
	}

	public GameOverStatsDialog() {
		super(GameFrame.getInstance(), "Event", true);
		setLayout(new GridLayout(3, 1));
		setLocationRelativeTo(GameFrame.getInstance());
		buildUIContents();

		pack();
		// REFACTOR THIS! MAGIC NUMBER
		if(getTitle() != null){
			FontMetrics fm = getFontMetrics(getFont());
			int width = fm.stringWidth(getTitle()) + 75; // MAGIC NUMBER, 75 is size of a "typical" window icon
			width = (int) Math.max(width*1.2, getPreferredSize().getWidth());
			setSize(new Dimension(width, getHeight()));
		}

		setVisible(true);
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
	}
}
